package com.bawei.lib_common.base

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

/**
 *作者：lxy
 *功能:懒加载Fragment基类
 *时间：2025/6/10
 */
abstract class LazyLoadFragment : Fragment() {

    private var isViewCreated = false // 视图是否已创建
    private var isFirstVisible = true // 是否首次可见
    private var isResumedBefore = false // 是否曾经Resume过

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("LazyLoad", "${javaClass.simpleName} - onCreateView")
        return inflater.inflate(getLayoutResId(), container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isViewCreated = true
        // 视图创建后，如果Fragment是可见的并且是第一次可见
        if (userVisibleHint && !isResumedBefore) {
            lazyLoad()
            isFirstVisible = false
            isResumedBefore = true
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && isViewCreated) {
            // 只有视图已创建后才进行加载
            if (isFirstVisible) {
                lazyLoad()
                isFirstVisible = false
                isResumedBefore = true
            } else {
                // 非首次可见，执行刷新操作
                onRefresh()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 如果Fragment曾经可见过，现在再次可见
        if (userVisibleHint && !isFirstVisible) {
            // 执行刷新操作
            onRefresh()
        }
    }

    // 需要子类实现的抽象方法
    abstract fun getLayoutResId(): Int
    abstract fun lazyLoad() // 首次可见时调用
    open fun onRefresh() {} // 每次可见时调用 - 可选项

    override fun onDestroyView() {
        super.onDestroyView()
        isViewCreated = false
        isFirstVisible = true
    }
}